package edu.nlplab.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class HelloController {

    @Resource
    private HttpServletRequest request;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap model) {
        model.addAttribute("message", "Hello world!");
        return "index";
    }

    @RequestMapping(value = "/uploadfiles", method = RequestMethod.GET)
    public String upload(ModelMap model) {
        return "uploadfiles1";
    }

    @RequestMapping(value = "/uploadfiles", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> addUploadFile(@RequestParam MultipartFile[] files) {

        //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
        String filePath = this.getFileUploadPath();
        Map<String, Object> model = new HashMap<String, Object>();
        int count = 0;
        for (MultipartFile file : files) {
            count++;
            if (file.isEmpty()) {
                model.put("errMsg", "请选择文件后上传!");
                return model;
            } else {
                String originalFilename = file.getOriginalFilename();
                System.out.println("第" + count + "文件原名: " + originalFilename);
                System.out.println("第" + count + "文件名称: " + file.getName());
                System.out.println("第" + count + "文件长度: " + file.getSize());
                System.out.println("第" + count + "文件类型: " + file.getContentType());
                System.out.println("========================================");
                try {
                    validateFile(file);

                    long now = System.currentTimeMillis();
                    long filesize = file.getSize();
                    long nameSuffix = now + filesize;
                    String fileType = originalFilename.substring(originalFilename.lastIndexOf('.'));

                    file.transferTo(new File(filePath + count + "_" + file.getName() + "_" + nameSuffix + fileType));
                } catch (IOException e){
                    model.put("Code", 0);
                    model.put("Msg", "文件[" + originalFilename + "]上传失败");
                    e.printStackTrace();
                    return model;
                } catch (Exception e) {
                    model.put("Code", 0);
                    model.put("Msg", e.getMessage());
                    return model;
                }
            }
        }
        model.put("Code", 1);
        model.put("Msg", "文件上传成功");
        return model;
    }

    @RequestMapping(value = "/uploadfiles1", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> addUploadFile(@RequestParam(value = "Filedata") MultipartFile file) {

        String filePath = this.getFileUploadPath();
        Map<String, Object> model = new HashMap<String, Object>();
        String originalFilename = file.getOriginalFilename();

        try {
            validateFileType(file);
            long now = System.currentTimeMillis();
            long filesize = file.getSize();
            long nameSuffix = now + filesize;
            String fileType = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String fileNamePre = originalFilename.substring(0, originalFilename.lastIndexOf('.'));

            file.transferTo(new File(filePath + fileNamePre + "_" + nameSuffix + fileType));
        } catch (IOException e) {
            model.put("Code", 0);
            model.put("Msg", "文件[" + originalFilename + "]上传失败");
            e.printStackTrace();
            return model;
        } catch (Exception e) {
            model.put("Code", 0);
            model.put("Msg", e.getMessage());
            return model;

        }

        model.put("Code", 1);
        model.put("Msg", "文件上传成功");
        return model;
    }

    // 校验文件
    private void validateFile(MultipartFile file) throws Exception {
        if (!file.getContentType().equals("text/plain")) {
            throw new Exception("上传文件必须为Txt格式！");
        }
    }

    private void validateFileType(MultipartFile file) throws Exception {
        String[] allow = {".txt", ".log"};
        String originalFilename = file.getOriginalFilename();

        String fileType = originalFilename.substring(originalFilename.lastIndexOf('.'));
        if(Arrays.binarySearch(allow, fileType) < 0)
            throw new Exception("上传文件必须为Txt格式！");
    }

    // 获取文件路径
    private String getFileUploadPath() {
        String prePath = request.getSession().getServletContext().getRealPath("/") + "static/uploads/";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String path = prePath + df.format(new Date()) + "/";
        File dir = new File(path);
        // 如果文件夹不存在，则创建
        if (!dir.exists()) {
            //System.out.println(path);
            dir.mkdirs();
        }
        return path;
    }

}